<template>
  <div class="app-container">
    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span style="color: red">* </span><span>时间地点</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <!-- <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="TimePlaceAdd"
            v-hasPermi="['eqxm:team:edit']"
            :disabled="!canChange"
            >新增</el-button
          >
          <span style="margin-left: 10px; color: #999; font-size: 14px"
            >实际打卡时间将根据此处填写时间而定</span
          >
        </el-col>
      </el-row> -->

      <el-table border :data="teamPlaceList" @selection-change="handleSelectionChange">
        <el-table-column label="地点" align="center" prop="provincial" />
        <el-table-column label="开始时间" align="center" prop="starttime" />
        <el-table-column label="结束时间" align="center" prop="endtime" />
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              :disabled="!canChange"
              v-hasPermi="['eqxm:teamPlace:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>
    </el-card>
    <!-- 添加或修改团队对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="7">
            <el-form-item label="开始时间" prop="starttime">
              <el-date-picker
                clearable
                size="small"
                v-model="form.starttime"
                type="date"
                @change="changeDate1"
                value-format="yyyy-MM-dd"
                placeholder="选择时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="结束时间" prop="endtime">
              <el-date-picker
                clearable
                size="small"
                v-model="form.endtime"
                type="date"
                @change="changeDate1"
                value-format="yyyy-MM-dd"
                placeholder="选择时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="地点" prop="college">
            <area-select v-if="isshow" @change="placeChange" style="padding: 0;"  type='text'  v-model="place" :data="$pcaa" :level="3"></area-select>
        </el-form-item> -->
        <el-row>
          <el-col :span="15">
            <el-form-item label="地点" prop="provincial">
              <el-input disabled v-model="form.provincial" placeholder="请下方地图选择" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="7">
            <el-form-item label="精度" prop="city">
              <el-input disabled v-model="form.city" placeholder="请地图选择" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="纬度" prop="region">
              <el-input disabled v-model="form.region" placeholder="请地图选择" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="">
          <el-button type="primary" @click="savePlace">添 加</el-button>
        </el-form-item>
      </el-form>
        <div id="myPageTop">
          <table>
            <tr>
              <td>
                <label>请输入关键字：</label>
              </td>
            </tr>

            <tr>
              <td>
                <input id="tipinput" />
              </td>
            </tr>
          </table>
        </div>
      <div id="mapDiv" ref="mapDiv" class="mapDiv">
      </div>
    </el-dialog>
    <el-button
      style="float: right; margin-top: 10px"
      type="primary"
      @click="next"
      >下一步</el-button
    >
    <el-button
      style="float: right; margin-right: 10px; margin-top: 10px"
      type="primary"
      @click="back"
      >上一步</el-button
    >
  </div>
</template>

<script>
import { listTeam, getTeam, delTeam, addTeam, updateTeam, exportTeam } from '@/api/eqxm/team';
import {
  listTeamPlace,
  getTeamPlace,
  delTeamPlace,
  addTeamPlace,
  updateTeamPlace,
  exportTeamPlace,
} from '@/api/eqxm/teamPlace';
import {
  listTeamTime,
  getTeamTime,
  delTeamTime,
  addTeamTime,
  updateTeamTime,
  exportTeamTime,
} from '@/api/eqxm/teamTime';
import CommonUtils from '@/utils/CommonUtils';
import AMap from 'AMap';
import { mapGetters } from 'vuex';
export default {
  name: 'TeamTimePlace',
  components: {
    AMap,
  },
  computed: {
    ...mapGetters(['roles', 'name']),
  },
  props:['isAdmin'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 团队表格数据
      teamList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        college: null,
        researchtopic: null,
        isimportant: null,
        presentation: null,
        presentationdetail: null,
        transportation: null,
        accommodation: null,
        publicity: null,
      },
      // 表单参数
      form: {
        provincial: null,
        city: '',
        region: '',
        starttime: '',
        endtime: '',
      },
      // 表单校验
      rules: {
        starttime: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
        endtime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
        provincial: [{ required: true, message: "地址不能为空", trigger: "blur" }],
      },
      place: [],
      teamId: '',
      isshow: false,
      time: '',
      adress: '',
      teamPlaceList: [],
      canChange: null,
    };
  },
  created() {
    this.init();
    this.getList();
  },
  mounted() {
    // this.initMap();
  },
  methods: {
    /** 查询团队列表 */
    getList() {
      const id = CommonUtils.getCurTeamInfo().id;
      this.teamId = id;
      getTeam(this.teamId).then(response => {
        console.log(response.data.createBy == this.name);
        this.canChange = response.data.createBy == this.name || this.isAdmin;
      });
      let newForm = {
        teamid: this.teamId,
      };
      listTeamPlace(newForm).then(response => {
        for (let i = 0; i < response.total; i++) {
        let t = response.rows[i].starttime.indexOf('-');
        response.rows[i].starttime =response.rows[i].starttime.substring(t + 1, response.rows[i].starttime.length);
        response.rows[i].endtime = response.rows[i].endtime.substring(t + 1, response.rows[i].endtime.length);
        }
        this.teamPlaceList = response.rows;
      });
    },

    init() {
      // const id = CommonUtils.getCurTeamInfo().id;
      // this.teamId=id;
      // if(id!=""){
      //   getTeamPlace(id).then(response => {
      //     if(response.data.id!=0){
      //   this.form=response.data
      //   /*    this.isshow = false;
      //      /* this.place.push(response.data.provincial);
      //       this.place.push(response.data.city);
      //       this.place.push(response.data.region);
      //       this.place.push(response.data.streets); */
      //       //console.log(this.place)
      //     }else{
      //      // this.isshow = true
      //     }
      //   });
      //   getTeamTime(id).then(response => {
      //     if(response.data.id!=0){
      //       this.time=response.data.teamtime;
      //     }
      //   });
      // }
    },
    // 判断日期前后
    changeDate1() {
      if (
        this.form.endtime != null &&
        this.form.endtime != "" &&
        this.form.endtime != undefined
      ) {
        console.log(this.form.starttime, this.form.endtime,"time")
        if (this.form.starttime > this.form.endtime) {// || this.form.endtime.includes(this.form.starttime)
          this.$message.error('结束时间需大于等于开始时间');
          this.form.endtime="";
        } else {
          console.log(222);
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    TimePlaceAdd() {
      this.reset();
      this.open = true;
      this.title = '添加时间地点';
      setTimeout(() => {
        this.initMap();
      }, 300);
    },
    // 表单重置
    reset() {
      this.form = {
        provincial: '',
        city: '',
        region: '',
        id: null,
        name: null,
        delFlag: null,
        college: null,
        createBy: null,
        researchtopic: null,
        isimportant: null,
        createTime: null,
        presentation: null,
        updateBy: null,
        presentationdetail: null,
        updateTime: null,
        transportation: null,
        accommodation: null,
        publicity: null,
        starttime: '',
        endtime: '',
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   //清空store的项目信息
    //   let teamInfo = {};
    //   CommonUtils.setCurTeamInfo(teamInfo);
    //   const vm = this;
    //   vm.$router.push({
    //     //核心语句
    //     path: '/team/teamManage', //跳转的路径
    //     query: { type: 0 },
    //   });
    // },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTeam(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改团队';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTeam(this.form).then(response => {
              if (response.code === 200) {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
              }
            });
          } else {
            addTeam(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              let teamInfo = {
                id: response,
              };
              CommonUtils.setCurTeamInfo(teamInfo);
              const id = CommonUtils.getCurTeamInfo();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除团队地点编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return delTeamPlace(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有团队数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportTeam(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    placeChange() {
      //console.log(this.place)
    },
    savePlace() {
      if (this.form.city == '') {
        this.$message.error('请选择地点');
        return;
      }
      console.log(this.form);
      if (this.form.starttime == '' || this.form.endtime == '') {
        this.$message.error('请选择时间');
        return;
      }

      let placeForm = {
        teamid: this.teamId,
        provincial: this.form.provincial,
        city: this.form.city,
        region: this.form.region,
        streets: this.form.streets,
        starttime: this.form.starttime,
        endtime: this.form.endtime,
      };
      addTeamPlace(placeForm).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess('修改成功');
          this.getList();
          this.open = false;
        }
      });
    },
    saveTime() {
      if (this.time == '') {
        this.$message.error('请选择时间');
        return;
      }
      let timeForm = {
        teamid: this.teamId,
        teamtime: this.time,
      };
      console.log(timeForm);
      addTeamTime(timeForm).then(response => {
        if (response.code === 200) {
        this.$modal.msgSuccess('修改成功');
        }
      });
    },
    // 初始化地图
    initMap() {
      let that = this;
      const _this = this;
      const map = new AMap.Map('mapDiv', {
        center: [120.148367, 30.248166],
        resizeEnable: true,
        zoom: 12,
        // lang: 'en'
      });
      this.map = map;
      that.map.on('click', function (e) {
        var lnglatXY = [e.lnglat.getLng(), e.lnglat.getLat()];
        console.log(lnglatXY, 'lnglatXY');

        that.initAdress(lnglatXY);
      });

      // 地图添加各种控件
      AMap.plugin(
        [
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.MapType',
          'AMap.Geolocation',
          'AMap.Autocomplete',
          'AMap.PlaceSearch',
        ],
        function () {
          // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
          map.addControl(new AMap.ToolBar());
          // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
          map.addControl(new AMap.MapType());

          // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
          // map.addControl(new AMap.Geolocation())

          // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
          map.addControl(new AMap.Scale());
        }
      );

      // 海量点的样式
      var style = [
        {
          // 必填参数,图标的地址
          url: 'https://a.amap.com/jsapi_demos/static/images/mass0.png',
          // 必填参数，图标显示位置偏移量，以图标的左上角为基准点（0,0）点，例如：anchor:new AMap.Pixel(5,5)
          anchor: new AMap.Pixel(6, 6),
          // 必填参数，图标的尺寸；例如：size:new AMap.Size(11,11)
          size: new AMap.Size(11, 11),
        },
        // 红色 未除治
        {
          url:
            this.baseURL +
            '/storage/dfs/display?path=group1/M00/00/0E/wKgABV-2IPiAEO2hAAAEJdf9ZKs794.png',
          anchor: new AMap.Pixel(6, 6),
          size: new AMap.Size(11, 11),
        },
        // 绿色  已经除治
        {
          url:
            this.baseURL +
            '/storage/dfs/display?path=group1/M00/00/0E/wKgABV-2IriAQ7-IAAAEJWeQRis039.png',
          anchor: new AMap.Pixel(6, 6),
          size: new AMap.Size(11, 11),
        },
        // 灰色以前的数据
        {
          url:
            this.baseURL +
            '/storage/dfs/display?path=group1/M00/00/0E/wKgABV-2IyGAS1xQAAAEJeELcZs238.png',
          anchor: new AMap.Pixel(6, 6),
          size: new AMap.Size(11, 11),
        },
      ];

      this.mass = new AMap.MassMarks(null, {
        // 图层的透明度，取值范围[0,1]，1代表完全不透明，0代表完全透明
        opacity: 0.6,
        // 图层叠加的顺序值，0表示最底层。默认zIndex：5
        zIndex: 111,
        // 指定鼠标悬停时的鼠标样式，自定义cursor，IE仅支持cur/ani/ico格式，Opera不支持自定义cursor
        cursor: 'pointer',
        style: style,
        // 表示是否在拖拽缩放过程中实时重绘，默认true，建议超过10000的时候设置false
        alwaysRender: false,
      });

      // 鼠标悬浮 弹出窗口
      var marker = new AMap.Marker({ content: ' ', map: map });

      this.mass.on('mouseover', function (e) {
        marker.setPosition(e.data.lnglat);
        marker.setLabel({ content: e.data.name });
      });

      // 海量点绑定到地图上
      this.mass.setMap(map);

      // 输入提示
      const autoOptions = {
        input: 'tipinput',
      };
      const auto = new AMap.Autocomplete(autoOptions);

      this.placeSearch = new AMap.PlaceSearch({
        map: map,
      }); // 构造地点查询类

      AMap.event.addListener(auto, 'select', this.select); // 注册监听，当选中某条记录时会触发

      //点击搜索出的mark点事件

      AMap.event.addListener(this.placeSearch, 'markerClick', function (e) {
        _this.$emit('bMapDate', e.data.location.lng, e.data.location.lat);
      });
    },
    initAdress(lnglatXY) {
      var that = this;
      const _this = this;
      AMap.plugin('AMap.Geocoder', function () {
        var geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: 'all',
        });
        geocoder.getAddress(lnglatXY, function (status, result) {
          console.log('addAdress2333');
          if (status === 'complete' && result.info === 'OK') {
            var address = result.regeocode.formattedAddress;

            //  that.address = address  //兑换地址
            console.log(lnglatXY[0], 'addAdress444');
            that.form.provincial = address;
            //	that.form.adress=address;
            that.form.city = lnglatXY[0];
            that.form.region = lnglatXY[1];
            //   that.$emit('getaddress', that.address, lnglatXY)
          } else {
            alert('无地址，请重新选择');
          }
        });
        // 清除所有标记

        that.map.clearMap();

        var marker = new AMap.Marker();
        that.map.add(marker);
        marker.setPosition(lnglatXY);
        /* 		that.form.city='12321'
		_this.form.city="888"
		debugger */
      });
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode);

      this.placeSearch.search(e.poi.name); // 关键字查询查询
    },

    handleMap(o, a) {
      this.$emit('bMapDate', o, a);
    },

    back() {
      this.$parent.jump(1);
    },
    next() {
      this.$parent.jump(3);
    },
  },
};
</script>
<style>
.area-select.large {
  width: 100%;
  line-height: 20px;
}
.area-select .area-selected-trigger {
  padding-top: 0px;
  padding-left: 2px;
}
.area-select-wrap .area-select {
  margin-left: 0px !important;
}

.mapDiv {
  width: 100%;
  height: 80vh;
  /* z-index: 9999; */
  /* background-color: #0d9bf2; */
}
.map-chart {
  position: relative;
  margin-bottom: 15px;
  width: 100%;
  height: 400px;
  border: 1px #dddddd solid;
}

/deep/.amap-logo,
/deep/ .amap-copyright {
  display: none !important;
}

#container {
  margin-bottom: 15px;
  width: 100%;
  height: 400px;
  border: 1px #dddddd solid;
  z-index: 999999;
  /* background-color: #0d9bf2; */
}

.button-group {
  position: absolute;
  bottom: 20px;
  right: 20px;
  font-size: 12px;
  padding: 10px;
}

.button-group .button {
  height: 28px;
  line-height: 28px;
  background-color: #0d9bf2;
  color: #fff;
  border: 0;
  outline: none;
  padding-left: 5px;
  padding-right: 5px;
  border-radius: 3px;
  margin-bottom: 4px;
  cursor: pointer;
}

.button-group .inputtext {
  height: 26px;
  line-height: 26px;
  border: 1px;
  outline: none;
  padding-left: 5px;
  padding-right: 5px;
  border-radius: 3px;
  margin-bottom: 4px;
  cursor: pointer;
}

#tip {
  background-color: #fff;
  padding-left: 10px;
  padding-right: 10px;
  position: absolute;
  font-size: 12px;
  right: 10px;
  top: 20px;
  border-radius: 3px;
  border: 1px solid #ccc;
  line-height: 30px;
}

.amap-info-content {
  font-size: 12px;
}

#myPageTop {
  position: absolute;
  /* position: fixed; */
  top: 261px;
  right: 100px;
  background: #fff none repeat scroll 0 0;
  border: 1px solid #ccc;
  margin: 10px auto;
  padding: 6px;
  font-family: 'Microsoft Yahei', '微软雅黑', 'Pinghei';
  font-size: 14px;
  z-index: 99999997;
  /* background-color: #0d9bf2; */
}
.amap-sug-result {
  z-index: 999999999;
}

#myPageTop label {
  margin: 0 20px 0 0;
  color: #666666;
  font-weight: normal;
  z-index: 99999999;
}

#myPageTop input {
  width: 170px;
}

#myPageTop .column2 {
  padding-left: 25px;
}
</style>
